package com.jinglin.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jinglin.common.UserThreadLocal;
import com.jinglin.pojo.Article;
import com.jinglin.pojo.ArticleCate;
import com.jinglin.pojo.User;
import com.jinglin.service.ArticleCateService;
import com.jinglin.service.ArticleService;
import com.jinglin.service.UserService;
import com.jinglin.utils.Result;
import com.jinglin.utils.UploadUtil;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

@RestController
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private ArticleCateService articleCateService;
    @Autowired
    private UploadUtil uploadUtil;
    @Autowired
    private UserService userService;
    @GetMapping("/my/article/list")
    public Result getArticleList(@RequestParam("pagenum") int pagenum,
                                 @RequestParam("pagesize") int pagesize,
                                 @RequestParam(value = "cate_id") String cate_id,
                                 @RequestParam(value = "state") String state){
        IPage<Article> page = new Page<>(pagenum, pagesize);
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(!cate_id.equals(""),Article::getCate_id,cate_id);
        wrapper.eq(!state.equals(""),Article::getState,state);
        IPage<Article> iPage = articleService.page(page, wrapper);
        return new Result(iPage.getRecords(),iPage.getTotal());
    }
    // 新增文章
    @Transactional
    @PostMapping("/my/article/add")
    public Result addArticle(@RequestParam("cover_img")MultipartFile cover_img, @RequestParam Map<Object,Object> map) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        Article article = BeanUtil.mapToBean(map,Article.class,false,null);
        if (article.getState().equals("已发布")){
            article.setState("1");
        } else {
            article.setState("0");
        }
        // 设置分类名称
        ArticleCate cate = articleCateService.getById(article.getCate_id());
        article.setCate_name(cate.getCate_name());
        // 设置目前的创建时间，并格式化
        // 创建日期对象
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z (z)", Locale.ENGLISH);

        TimeZone timeZone = TimeZone.getTimeZone("GMT+08:00");
        sdf.setTimeZone(timeZone);
            // 格式化当前日期
        String formattedDate = sdf.format(now);
        article.setPub_date(formattedDate);
        // 将图片保存到minio中去
        String url = uploadUtil.fileUpload(cover_img);
        System.out.println(url);
        article.setCover_img(url);
        // 添加文章用户信息
        User user = UserThreadLocal.getUser();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,user.getUsername());
        User one = userService.getOne(wrapper);
        article.setUsername(one.getUsername());
        article.setAuthor_id(one.getId());
        article.setNickname(one.getNickname());


        articleService.save(article);
        return Result.success("新增成功！");
    }

    // 编辑文章
    @Transactional
    @PutMapping("/my/article/update")
    public Result updateArticle(@RequestParam("cover_img")MultipartFile cover_img, @RequestParam Map<String,String> map) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        Article article = BeanUtil.mapToBean(map,Article.class,false,null);
/*        article.setId(map.get("id"));
        article.setTitle(map.get("content"));
        article.setTitle(map.get("title"));
        article.setState(map.get("state"));*//*

        // 设置分类名称
        article.setCate_name(map.get("cate_name"));
        article.setCate_id(map.get("cate_id"));
        // 设置时间
        article.setPub_date(map.get("pub_date"));*/
        // 将图片保存到minio中去
        String url = uploadUtil.fileUpload(cover_img);
        System.out.println(url);

        article.setCover_img(url);
        articleService.updateById(article);
        return Result.success("新增成功！");
    }



    // 根据id获取文章详情
    @GetMapping("/my/article/info")
    public Result getArticleInfo(@RequestParam("id") String id){
        Article article = articleService.getById(id);
        return Result.success(article);
    }
    // 根据id删除文章
    @DeleteMapping("/my/article/info")
    public Result deleteArticle(@RequestParam("id") String id){
        articleService.removeById(id);
        return Result.success("删除成功！！");
    }
    // 根据id推荐文章
    @PostMapping("/my/article/recommend")
    public Result recommend(@RequestBody Map<String,String> map){
        String id = map.get("id");
        LambdaUpdateWrapper<Article> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Article::getRecommend,1);
        wrapper.eq(Article::getId,id);
        articleService.update(wrapper);
        return Result.success("推荐成功！！！");
    }
    // 根据id取消推荐文章
    @PostMapping("/my/article/unRecommend")
    public Result unRecommend(@RequestBody Map<String,String> map){
        String id = map.get("id");
        LambdaUpdateWrapper<Article> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Article::getRecommend,0);
        wrapper.eq(Article::getId,id);
        articleService.update(wrapper);
        return Result.success("取消推荐成功！！！");
    }

}
